package io;

import java.io.*;
import java.util.Scanner;
import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Li_DaChiZi
 * Date: 2025/7/4
 * Time: 13:59
 */
// 递归按照文件内容 查询
public class Demo19 {
    public static void doSearch(File f , String key) {
        StringBuilder stringBuilder = new StringBuilder();
        try (Reader reader = new FileReader(f)){
            char[] buffer = new char[1024];
            while (true) {
                int n = reader.read(buffer);
                if (n == -1 ) {
                    break;
                }
                String s = new String(buffer,0,n);
                stringBuilder.append(s);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if (stringBuilder.indexOf(key) == -1) {
            return;
        }
        //招到了
        System.out.println("找到匹配的文件" + f.getAbsolutePath());
    }

    public static void scan (File file , String key) {
        if (!file.isDirectory()) {
            return;
        }
        File[] files = file.listFiles();
        if (files == null || files.length == 0) {
            return;
        }
        for (File f: files) {
            if (f.isFile()) {
                doSearch(f,key);
            }else {
                scan(f,key);
            }
        }
    }


    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要搜索的路径");
        String rootPath = scanner.next();
        File rootFile = new File(rootPath);
        if (!rootFile.isDirectory()) {
            System.out.println("输入路径有误！");
            return;
        }
        System.out.println("请输入要查询的关键词：");
        String key = scanner.next();
        //进行递归
        scan( rootFile, key);
    }
}
